import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import 'package:flutter_stripe_payment/flutter_stripe_payment.dart';
import 'package:tobias/tobias.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:chewie/chewie.dart';
import 'package:video_player/video_player.dart';

import '../../blocs/order_detail.dart';

import 'package:flutter/material.dart' as fm;

class HistoryDetailScreen extends StatefulWidget {
  final String detail;
  const HistoryDetailScreen(this.detail, {Key? key}) : super(key: key);
  @override
  _HistoryDetailScreenState createState() => _HistoryDetailScreenState();
}

class _HistoryDetailScreenState extends State<HistoryDetailScreen> {
  late Map lm_detail;
  late CancelFunc cancelLoading;
  final _stripePayment = FlutterStripePayment();

  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;

  Future<void>? _initializeVideoPlayerFuture;

  _initVideo() async {
    await _videoPlayerController.initialize();
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      aspectRatio: 3 / 2,
      autoPlay: true,
      looping: false,
      showControls: true,
      autoInitialize: true,
      // materialProgressColors: ChewieProgressColors(
      //   playedColor: Colors.red,
      //   handleColor: Colors.blue,
      //   backgroundColor: Colors.grey,
      //   bufferedColor: Colors.lightGreen,
      // ),
      // placeholder: Container(
      //   color: Colors.grey,
      // ),
      // autoInitialize: true,
    );
  }

  @override
  initState() {
    super.initState();
    stripeInit();
    lm_detail = jsonDecode(widget.detail);
    var lv_video_url = '';
    if ((lm_detail['packing_video'] ?? {}).isNotEmpty)
      lv_video_url = lm_detail['packing_video']['video_url'];
    _videoPlayerController = VideoPlayerController.network(lv_video_url);
    // 'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4');

    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      aspectRatio: 3 / 2,
      autoPlay: false,
      looping: false,
      // showControls: true,
      autoInitialize: true,
      // materialProgressColors: ChewieProgressColors(
      //   playedColor: Colors.red,
      //   handleColor: Colors.blue,
      //   backgroundColor: Colors.grey,
      //   bufferedColor: Colors.lightGreen,
      // ),
      // placeholder: Container(
      //   color: Colors.grey,
      // ),
      // autoInitialize: true,
    );
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  stripeInit() async {
    await _stripePayment.setStripeSettings(App3rdKey.stripe_key, App3rdKey.applepay_id);
    print(_stripePayment);
  }

  @override
  Widget build(BuildContext context) {
    OrderDetailBloc _orderDetail = Provider.of<OrderDetailBloc>(context, listen: false);

    _confirm() async {
      AppSession.bottomIndex = 1;
      _orderDetail.clear();
      Navigator.pushNamedAndRemoveUntil(context, '/', (_) => false);
    }

    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            child: Icon(
              Icons.chevron_left,
              color: AppColor.blackMain,
              size: 32,
            ),
          ),
        ),
        title: Text(
          '订单 #' + lm_detail['oid'].toString(),
          style: TextStyle(color: AppColor.blackMain),
        ),
      ),
      body: SingleChildScrollView(
        child: Container(
          child: Column(
            children: <Widget>[
              _cardAddressBlock(),
              _deliveryTimeBlock(),
              if ((lm_detail['available_payment_channels'] ?? {}).isNotEmpty)
                _paymentMethodBlock(context, _orderDetail),
              if ((lm_detail['available_payment_channels'] ?? {}).isNotEmpty) _commentBlock(),
              if ((lm_detail['available_payment_channels'] ?? {}).isNotEmpty) _summaryBlock(),
              if ((lm_detail['packing_video'] ?? {}).isNotEmpty) _packingVideoBlock(),
              _itemListBlock(),
              SizedBox(
                height: 88.h,
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: (lm_detail['status'] != 0)
          ? Container()
          : Container(
              // padding: EdgeInsets.symmetric(horizontal: 20),

              height: 80.h,
              width: ScreenUtil().screenWidth,
              child: RaisedButton(
                color: AppColor.yellowMain,
                onPressed: () async {
                  var lv_pmid = '';
                  // if ((lm_detail['payment_cards'] ?? {})
                  //     .isNotEmpty) if ((_cart.ticket['payment_cards']['2'] ?? {}).isNotEmpty)
                  //   lv_pmid = _cart.ticket['payment_cards']['2']['pmid'];

                  if ((AppSession.creditcard['pmid'] ?? '').isNotEmpty)
                    lv_pmid = AppSession.creditcard['pmid'];
                  if ((lv_pmid.isEmpty) && (_orderDetail.payment_channel == 2)) {
                    AppPopupService.showAlertSimple('E', '信息错误', '如果选择信用卡请先维护卡片信息');
                  } else {
                    Map<String, dynamic> lm_param = {
                      "oid": lm_detail['oid'],
                      'payment_channel': _orderDetail.payment_channel
                    };
                    var lm_result = await _orderDetail.orderRepay(lm_param);

                    if ((lm_result ?? {}).isNotEmpty) {
                      cancelLoading = BotToast.showLoading(duration: Duration(seconds: 10));
                      AppPopupService.showAlertSimple('W', '准备支付', '加载中.....',
                          iv_duration: Duration(seconds: 1));

                      switch (_orderDetail.payment_channel) {
                        case 2:
                          {
                            var intentResponse = await _stripePayment.confirmPaymentIntent(
                                lm_result['payment_intent'],
                                lv_pmid,
                                lm_result['charge_total'],
                                true);
                            switch (intentResponse.status) {
                              case PaymentResponseStatus.succeeded:
                                {
                                  cancelLoading();
                                  AppPopupService.showAlertSimple('S', '下单成功', '请到历史订单里查看',
                                      confirm: _confirm);

                                  print(intentResponse.paymentIntentId);
                                  print(intentResponse);
                                }
                                break;
                              case PaymentResponseStatus.failed:
                                {
                                  cancelLoading();
                                  AppPopupService.showAlertSimple('E', '支付失败', '请到历史订单里查看',
                                      confirm: _confirm);

                                  print(intentResponse);
                                  break;
                                }
                              default:
                                {
                                  cancelLoading();
                                  _confirm();
                                  print(intentResponse);
                                }
                                break;
                            }
                            break;
                          }

                        case 11:
                          {
                            await aliPay(lm_result['payment_intent']);
                            cancelLoading();
                            _confirm();
                            break;
                          }
                        case 21:
                          {
                            // Map payResult;
                            try {
                              print('aaa');

                              var lm_intent = lm_result['payment_intent'];
                              fluwx
                                  .payWithWeChat(
                                appId: lm_intent['appid'],
                                partnerId: lm_intent['partnerid'],
                                prepayId: lm_intent['prepayid'],
                                packageValue: lm_intent['package'],
                                nonceStr: lm_intent['noncestr'],
                                timeStamp: int.parse(lm_intent['timestamp']),
                                sign: lm_intent['sign'],
                              )
                                  .then((data) {
                                print("---> $data");
                                cancelLoading();
                                _confirm();
                              });
                            } on Exception catch (e) {
                              print(e);
                            }
                            break;
                          }
                      }
                    }
                  }
                },
                child: Text(
                  '确认付款',
                  style: TextStyle(
                    fontSize: 18.sp,
                  ),
                ),
              ),
            ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  Widget _itemComp(Map im_item) {
    return Container(
      height: 66.h,
      padding: EdgeInsets.symmetric(horizontal: 28.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              if ((im_item['image_url'] ?? '').isNotEmpty)
                Container(
                  width: 50.w,
                  height: 50.h,
                  child: CachedNetworkImage(
                    imageUrl: im_item['image_url'],
                    fit: BoxFit.cover,
                  ),
                ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(left: 6.w),
                    child: Text(
                      im_item['name'] ?? '',
                      softWrap: true,
                      overflow: TextOverflow.fade,
                    ),
                  ),
                  (im_item['status'] == 90)
                      ? Container(
                          padding: EdgeInsets.only(left: 6.w),
                          child: Text(
                            (im_item['fulfill_amount'] == null)
                                ? '(' + '缺货' + ')'
                                : '(' +
                                    '商品部分缺货,  可送' +
                                    (im_item['fulfill_amount'] ?? 0).toString() +
                                    '个)',
                            softWrap: true,
                            overflow: TextOverflow.fade,
                            style: TextStyle(
                              // fontSize: fontSize.sp,
                              color: Colors.red,
                            ),
                          ),
                        )
                      : Container(
                          padding: EdgeInsets.only(left: 6.w),
                          child: Text(
                            '(' + (im_item['status_desc'] ?? '') + ')',
                            softWrap: true,
                            overflow: TextOverflow.fade,
                            style: TextStyle(
                              // fontSize: fontSize.sp,
                              color: Colors.grey,
                            ),
                          ),
                        ),
                ],
              ),
            ],
          ),
          Text('\$' + im_item['price'].toString() + 'x' + im_item['amount'].toString()),
        ],
      ),
    );
  }

  Widget _cardAddressBlock() {
    return Card(
      child: Container(
        height: 140.h,
        padding: EdgeInsets.symmetric(horizontal: 28.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _headerText('配送信息'),
            Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(right: 10.w),
                  child: Icon(
                    // MaterialCommunityIcons.clipboard_account,
                    Icons.paste,
                    color: AppColor.yellowText,
                  ),
                ),
                _headerText(lm_detail['consignee_info']['consignee_name'] ?? '', fontSize: 13),
              ],
            ),
            Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(right: 10.w),
                  child: Icon(
                    // MaterialCommunityIcons.phone_in_talk,
                    Icons.phone_bluetooth_speaker,
                    color: AppColor.yellowText,
                  ),
                ),
                _headerText(lm_detail['consignee_info']['consignee_phone'] ?? '', fontSize: 13),
              ],
            ),
            Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(right: 10.w),
                  child: Icon(
                    // MaterialCommunityIcons.map_marker_radius,
                    Icons.map_rounded,
                    color: AppColor.yellowText,
                  ),
                ),
                Container(
                  width: 260.w,
                  height: 20.h,
                  child: Builder(builder: (context) {
                    return _headerText(lm_detail['consignee_info']['addr'], fontSize: 13);
                  }),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _deliveryTimeBlock() {
    return Card(
      child: Container(
        width: double.infinity,
        height: 80.h,
        // width: 370.h,
        padding: EdgeInsets.symmetric(horizontal: 28.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _headerText('配送时间'),
            _contentText(lm_detail['dl_date'] + ' ' + lm_detail['dl_window']),
          ],
        ),
      ),
    );
  }

  Widget _packingVideoBlock() {
    return Card(
      child: Container(
        height: 260.h,
        // padding: EdgeInsets.symmetric(horizontal: 28.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Chewie(
              controller: _chewieController,
            ),

            // _contentText(lm_detail['dl_date'] + ' ' + lm_detail['dl_window']),
          ],
        ),
      ),
    );
  }

  Widget _paymentMethodBlock(BuildContext context, OrderDetailBloc ib_order) {
    return Card(
      child: Container(
        height: 80.h,
        padding: EdgeInsets.symmetric(horizontal: 28.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                _headerText('支付方式'),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    var lv_channels = Uri.encodeQueryComponent(
                        jsonEncode(lm_detail['available_payment_channels']));
                    App.router.navigateTo(
                        context, AppRoutes.historyPaymentChannel + '?channels=${lv_channels}');
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      Icon(
                        // MaterialCommunityIcons.square_edit_outline,
                        Icons.edit,
                        color: AppColor.yellowText,
                      ),
                      _contentText('修改', fontSize: 13),
                    ],
                  ),
                ),
              ],
            ),
            // findPaymentChannelDescr(lm_detail['payment_channel'] )
            _contentText(ib_order.findPaymentChannelDescr(lm_detail, ib_order.payment_channel)),
            // _contentText(lm_detail['payment_method']['brand'] +
            //     ' ****' +
            //     lm_detail['payment_method']['last4']),
          ],
        ),
      ),
    );
  }

  Widget _commentBlock() {
    return Card(
      child: Container(
        height: 80.h,
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 28.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _headerText('备注'),
            _contentText(lm_detail['comment']),
          ],
        ),
      ),
    );
  }

  Widget _summaryBlock() {
    return Card(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 28.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                _headerText('Sub total:'),
                _headerText(lm_detail['fees_detail']['pretax'].toStringAsFixed(2)),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                _headerText('Tax:'),
                _headerText(lm_detail['fees_detail']['tax_total'].toStringAsFixed(2)),
              ],
            ),

            // VIP &  Vouvher
            if ((lm_detail['active_discounts'] ?? []).isNotEmpty)
              for (var ll_discount in lm_detail['active_discounts'])
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    _headerText(ll_discount['name']),
                    _contentText(
                      '-' + ll_discount['amount_off'].toStringAsFixed(2),
                    ),
                  ],
                ),

            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                _headerText('Total:'),
                _contentText(lm_detail['fees_detail']['charge_total'].toStringAsFixed(2)),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _itemListBlock() {
    return ListView.builder(
      primary: false,
      shrinkWrap: true,
      itemCount: lm_detail['items'].length ?? 0,
      itemBuilder: (BuildContext context, int index) {
        var _item = lm_detail['items'][index];
        print(_item);
        return Column(
          children: <Widget>[
            _itemComp(_item),
            Divider(
              height: 1.0,
              indent: 20.0,
              endIndent: 20.0,
            ),
          ],
        );
      },
    );
  }

  Widget _headerText(
    String iv_str, {
    int fontSize = 15,
  }) {
    return Text(
      iv_str,
      softWrap: true,
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        fontSize: fontSize.sp,
        color: AppColor.blackMain,
      ),
    );
  }

  Widget _contentText(
    String iv_str, {
    int fontSize = 15,
    int maxLines = 3,
  }) {
    return Text(
      iv_str,
      softWrap: true,
      overflow: TextOverflow.fade,
      maxLines: maxLines,
      style: TextStyle(
        fontSize: fontSize.sp,
        color: AppColor.yellowText,
      ),
    );
  }
}
